<template>
  <div class="header">
    <!-- 顶部公告 -->
    <HeaderTop/>
    <a-row class="header-container">
      <a-col :span="2" :xs="4" class="logo-container">
        <a href="/" class="logo">
          <!-- <h1>LANNUAN</h1> -->
          <img :src="SVG_ICONS.logoimg" class="logo-image" alt="LANNUAN" />
        </a>
      </a-col>
      <a-col :span="12" :xs="14" class="nav-container">
        <HeaderTabs v-show="!isMobile"/>
      </a-col>
      <a-col :span="6" :xs="6" class="user-actions">
        <div class="actions-container">
          <div v-if="!showSearchInput && !userStore.isLoggedIn" class="user-links">
            <a href="/login" class="action-item login-link">Hi, Sign in</a>
            <a href="/login" class="action-item register-link">Register for free gifts</a>
          </div>

          <!-- 添加登录后显示的用户名和下拉菜单 -->
          <a-dropdown v-if="!showSearchInput && userStore.isLoggedIn" placement="bottom">
            <div class="user-account action-item">
              <span class="user-greeting">Hi, Ya</span>
              <down-outlined class="dropdown-icon" />
            </div>
            <template #overlay>
              <a-menu class="user-dropdown-menu">
                <a-menu-item key="account">
                  <a href="/user">My account</a>
                </a-menu-item>
                <a-menu-item key="signout" @click="handleSignOut">
                  <span>Sign out</span>
                </a-menu-item>
                <a-menu-item key="cancelAccount" @click="handleCancelAccount">
                  <span>Cancel the account</span>
                </a-menu-item>
              </a-menu>
            </template>
          </a-dropdown>

          <div class="search-container" :class="{ 'show-search': showSearchInput && !isMobile }">
            <a-input
                v-if="showSearchInput && !isMobile"
                :bordered="false"
                v-model:value="searchQuery"
                placeholder="Search..."
                class="search-input"
                @pressEnter="handleSearch"
                ref="searchInputRef"
            />
          </div>
          <div class="action-item search-icon-container">
            <a-button type="text" shape="circle" @click="toggleSearch">
              <template #icon>
                <CloseOutlined :style="{fontSize: '16px'}" v-if="showSearchInput"/>
                <SearchOutlined :style="{fontSize: '16px'}" v-else/>
              </template>
            </a-button>
          </div>
          <a href="/user/wishlist" class="action-item" @click="hasNewFavorite = false;">
            <a-button type="text" shape="circle">
              <template #icon>
                <a-badge :dot="hasNewFavorite">
                  <HeartOutlined :style="{fontSize: '16px'}"/>
                </a-badge>
              </template>
            </a-button>
          </a>
<!--          <a href="/cart" class="action-item">-->
<!--            <a-button type="text" shape="circle">-->
<!--              <template #icon>-->
<!--                <ShoppingOutlined :style="{fontSize: '16px'}"/>-->
<!--              </template>-->
<!--              <a-badge :count="cartList.total || 0" :offset="[0, -5]" size="small"/>-->
<!--            </a-button>-->
<!--          </a>-->

          <a-popconfirm
              v-if="userStore.isLoggedIn"
              placement="bottom"
              :show-cancel="false"
              :show-ok="false"
              :show-icon="false"
              :ok-button-props="{ style: { display: 'none' } }"
              :cancel-button-props="{ style: { display: 'none' } }"
              :overlay-style="{ padding: 0, background: '#f6f6f6', margin: 0 }"
              :icon="null"
          >
            <div class="cart-total-box">
              <a href="#" class="action-item">
                <a-button type="text" shape="circle" class="iconButton">
                  <template #icon>
                    <ShoppingOutlined :style="{fontSize: '16px'}"/>
                  </template>
                  <a-badge :count="cartList.total || 0" :offset="[0, -5]" size="small"/>
                </a-button>
              </a>
            </div>
            <template #description>
              <div class="cart-popup">
                <Cart :cartList="cartList" :cartTotalPrice="cartCount"/>
              </div>
            </template>
          </a-popconfirm>
          <div v-else class="cart-total-box" @click="goToLogin">
            <a href="/login" class="action-item">
              <a-button type="text" shape="circle" class="iconButton">
                <template #icon>
                  <ShoppingOutlined :style="{fontSize: '16px'}"/>
                </template>
              </a-button>
            </a>
          </div>
          <!-- 货币 -->
          <a-dropdown v-model:open="visible" trigger="click" @click="handleMenuClick">
              <div class="currency-flag-container">
                <a-image
                  v-if="currencyStore.currentCurrency?.country_flag"
                  :src="currencyStore.currentCurrency.country_flag"
                  :preview="false"
                  class="currency-flag"
                    style="border: 2px solid #000; border-radius: 50%;"
                  fallback="/path/to/default-flag.png"
                  alt="currencyFlag"
                />
              </div>
            </a-dropdown>

          <a class="action-item" v-if="isMobile">
            <a-button class="menu-toggle" type="text" @click="showMobileMenu = true">
              <template #icon>
                <MenuOutlined :style="{fontSize: '16px'}"/>
              </template>
            </a-button>
          </a>
        </div>
      </a-col>
    </a-row>
    <a-drawer
          title="CHANGE COUNTRY"
          :closable="false"
          :open="open"
          width=500
          :maskStyle="{backgroundColor: 'rgba(0, 0, 0, 0.8)'}"
          @close="onClose"
      >
        <p>Location</p>
        <Currency @closeDrawer="onClose"/>
    </a-drawer>
    <!-- 移动端搜索框 -->
    <div class="mobile-search-container" v-if="showSearchInput && isMobile">
      <div class="mobile-search-wrapper">
        <a-input
            v-model:value="searchQuery"
            :bordered="false"
            :allowClear="true"
            placeholder="Search..."
            class="mobile-search-input"
            @pressEnter="handleSearch"
            ref="mobileSearchInputRef"
        >
          <template #prefix>
            <SearchOutlined :style="{fontSize: '16px', color: '#bfbfbf'}" />
          </template>
        </a-input>
        <div class="popular-searches">
          <p class="popular-title">Popular searches</p>
          <a href="/search?q=iconic%20women%20fragrance" class="popular-item">iconic women fragrance</a>
          <a href="/search?q=bag" class="popular-item">bag</a>
          <a href="/search?q=shoes" class="popular-item">shoes</a>
        </div>
      </div>
    </div>

    <!-- 移动端菜单 -->
    <a-drawer
        :title="mobileMenuTitle"
        placement="left"
        :open="showMobileMenu"
        @close="showMobileMenu = false"
        width="90%"
    >
      <!-- 主菜单 -->
      <div v-if="!currentCategory">
        <a-list>
          <a-list-item v-for="item in mobileTabs" :key="item.id" @click="showSubCategory(item)">
            <div class="mobile-menu-item">
              {{ item.name }}
              <right-outlined />
            </div>
          </a-list-item>
          <a-list-item v-if="userStore.isLoggedIn" @click="handleSignOut">
            <div class="mobile-menu-item">
              Sign out
            </div>
          </a-list-item>
          <a-list-item v-else>
            <a href="/login" class="mobile-menu-item">
              Sign in or Register
            </a>
          </a-list-item>
          <a-list-item>
            <a href="/store-locations" class="mobile-menu-item">
              Store locations
            </a>
          </a-list-item>
        </a-list>
      </div>

      <!-- 子分类菜单 -->
      <div v-else>
        <div class="submenu-header">
          <left-outlined class="back-button" @click="goBackToMain" />
          <span>{{ currentCategory.title }}</span>
        </div>
        <a-list>
          <a-list-item v-for="subItem in currentCategory.children" :key="subItem.id" @click="handleCategoryClick(subItem)">
            <div class="mobile-menu-item">
              <a :title="subItem.name" :href="`/classify/${subItem.url}-${subItem.id}.html`" target="_self">{{ subItem.name }}</a>
              <right-outlined v-if="subItem.children && subItem.children.length > 0" />
            </div>
          </a-list-item>
        </a-list>
      </div>
    </a-drawer>
  </div>
</template>

<script lang="ts" setup>
import {ref, onMounted, onUnmounted, nextTick,computed} from 'vue';
import type {Ref} from 'vue';
import {SearchOutlined, HeartOutlined, ShoppingOutlined, MenuOutlined, CloseOutlined, DownOutlined, RightOutlined, LeftOutlined} from '@ant-design/icons-vue';
import HeaderTabs from './HeaderTabs.vue';
import {useUserStore} from '@/store/user';
import {useCartStore} from '@/store/cart.ts';
import {Local, Session} from "@/utils/storage.ts";
import {getCarts} from "@/api/goods.ts";
import Cart from "@/components/cart/index.vue"
import {type MenuProps, message} from "ant-design-vue";
import {useRouter} from "vue-router";
import mitt from '@/utils/mitt.ts'; // 导入mitt事件总线
import HeaderTop  from './HeaderTop.vue';
import emitter from '@/utils/eventBus';
import {useCommonStore, useCurrencyStore} from '@/store'
import Currency from "@/components/common/currency.vue"
import SVG_ICONS from "@/assets/SVG_ICONS.ts";
const cartStore = useCartStore();
const userStore = useUserStore();
const router = useRouter();
// 类型定义
interface ApiResponse<T> {
  code: number;
  result: T;
  message?: string;
}
interface CartItem {
  sku: {
    spec: string;
    color: string | null;
    size: string | null;
    price: number;
  };
  num: number;
  total: number;
}
// 购物车商品数量
interface CartList {
  total: number;
  data: CartItem[];
}
const cartList = ref<CartList>({
  total: 0,
  data: []
});
const visible = ref(false);//货币
const currencyStore = useCurrencyStore()
const open = ref<boolean>(false); //货币选择右拉框
let options = computed(() => {
  return currencyStore.currencies;
})
const cartCount = ref(0);
// 是否为移动端
const isMobile = ref(false);
// 是否显示移动端菜单
const showMobileMenu = ref(false);
const mobileMenuTitle = ref('');
const mobileTabs = ref<any[]>([]);
// 当前选中的分类
const currentCategory = ref<any>(null);
// 分类历史记录，用于返回上一级
const categoryHistory = ref<any[]>([]);
// 是否显示搜索输入框
const showSearchInput = ref(false);
// 搜索输入框的值
const searchQuery = ref('');
// 搜索输入框的ref
const searchInputRef = ref<HTMLInputElement | null>(null);
const mobileSearchInputRef = ref<HTMLInputElement | null>(null);
// 是否登录
const isLogin = !!Local.get('user_token');
// 收藏列表更新
const hasNewFavorite = ref<boolean>(false);
// 获取移动端头部数据
const fetchMobileMenuData = async () => {
  const tabList = Session.get('tab')

  if(tabList && tabList.length > 0){
    mobileTabs.value = tabList;
    return;
  }
};

const handleMenuClick: MenuProps['onClick'] = e => {
  open.value = true;
};
const onClose = () => {
  open.value = false;
};

onMounted(() => {
  if(isLogin){
    getCartList();
    mobileMenuTitle.value = `Hi,${userStore.userInfo.name}`;
  }else {
    mobileMenuTitle.value = 'Hi, Sign in';
  }
   // 货币货币列表
   if (Local.get('currencies')) {
    setInterval(async () => {
      Local.remove('currencies')
      // 初始化加载货币数据
      currencyStore.fetchCurrencies()
    }, 300000)
  } else {
    currencyStore.fetchCurrencies()
  }
  checkMobile();
  fetchMobileMenuData();

  // 初始化分类历史记录
  categoryHistory.value = [];
  // getCartCount();
  window.addEventListener('resize', checkMobile);

  // 监听购物车添加商品事件
  mitt.on('addCart', () => {
    getCartList(); // 刷新购物车数据
  });

  // 监听购物车添加商品事件
  emitter.on('getCartList', () => {
    getCartListApi(); // 刷新购物车数据
  });

  // 监听收藏事件
  emitter.on('newFavorite', () => {
    hasNewFavorite.value = true;
  });
});

onUnmounted(() => {
  window.removeEventListener('resize', checkMobile);

  // 移除事件监听
  mitt.off('addCart');

  emitter.off('newFavorite');

  emitter.off('getCartList');
});

// 显示子分类
const showSubCategory = (category: any) => {
  categoryHistory.value.push(currentCategory.value);
  currentCategory.value = category;
  mobileMenuTitle.value = category.title;
};

// 返回上一级分类
const goBackToMain = () => {
  currentCategory.value = categoryHistory.value.pop();
  mobileMenuTitle.value = currentCategory.value ? currentCategory.value.title : 'Hi, Sign in';
};

// 处理分类点击
const handleCategoryClick = (category: any) => {
  if (category.children && category.children.length > 0) {
    showSubCategory(category);
  } else if (category.url) {
    // 如果有URL则跳转
    window.location.href = category.url;
    showMobileMenu.value = false;
  }
};

// 切换搜索输入框的显示状态
const toggleSearch = () => {
  showSearchInput.value = !showSearchInput.value;

  if (showSearchInput.value) {
    nextTick(() => {
      if (isMobile.value) {
        if (mobileSearchInputRef.value) {
          mobileSearchInputRef.value.focus();
        }
      } else if (searchInputRef.value) {
        searchInputRef.value.focus();
      }
    });
  } else {
    // 隐藏搜索框时清空搜索内容
    searchQuery.value = '';
  }
};

// 处理搜索请求
const handleSearch = () => {
  if (searchQuery.value.trim()) {
    router.push({
      path: '/search',
      query: {
        keyword: searchQuery.value
      }
    });
  }
};

// 检查是否为移动端
const checkMobile = () => {
  isMobile.value = window.innerWidth < 768;
};

// 获取购物车数量
const getCartCount = () => {
  try {
    const cartData = localStorage.getItem('cart');
    if (cartData) {
      const cart = JSON.parse(cartData);
      cartCount.value = Array.isArray(cart) ? cart.length : 0;
    }
  } catch (error) {
    console.error('获取购物车数据失败:', error);
    cartCount.value = 0;
  }
};
//获取购物车列表
const getCartList = async () => {
  const shopCart = cartStore.getShopCart();
  if(shopCart){
    cartCount.value = 0;
    cartList.value = dealWith(shopCart);
  } else {
    await getCartListApi();
  }
};

const getCartListApi = async () => {
  try {
    const res = await getCarts() as ApiResponse<CartList>;
    if (res.code === 200) {
      cartCount.value = 0;
      cartStore.setShopCart(res.result);
      cartList.value = dealWith(res.result);
    }
  } catch (error) {
    console.error('Failed to fetch cart:', error);
  }
};
const dealWith = (cart: CartList): CartList => {
  cart.data.forEach((item: CartItem) => {
    const colorMatch = item.sku.spec.match(/Color:(.*?);/);
    item.sku.color = colorMatch ? colorMatch[1] : null;
    const sizeMatch = item.sku.spec.match(/Size:(.*)/);
    item.sku.size = sizeMatch ? sizeMatch[1] : null;
    item.total = item.sku.price * item.num;
    cartCount.value += item.sku.price * item.num;
  });
  return cart;
};
const goToLogin = () => {
  message.error('Please login first');
  router.push('/login');
};

// 处理退出登录
const handleSignOut = () => {
  userStore.logout();
  message.success('Successfully signed out');
  router.push('/login');
};

// 处理注销账号
const handleCancelAccount = () => {
  router.push('/cancelAccount');
};

</script>

<style lang="scss" scoped>
.header {
  width: 100%;
  border-bottom: 1px solid #e8e8e8;
  background-color: #fff;
  position: sticky;
  top: 0;
  z-index: 1000;
}

.header-container {
  max-width: 1850px;
  margin: 0 auto;
  display: flex;
  align-items: center;
  height: 64px;
  padding: 0 15px;
}

.logo-container {
  display: flex;
  align-items: center;
}

.logo {
  text-decoration: none;

  h1 {
    margin: 0;
    font-size: 28px;
    font-weight: bold;
    letter-spacing: 1px;
    color: #262626;
    text-transform: uppercase;
  }
}

.nav-container {
  display: flex;
  justify-content: center;
}

.main-menu {
  background: transparent;
  border-bottom: none;

  :deep(.ant-menu-item) {
    margin: 0 10px;
    padding: 0 5px;
    font-weight: 500;

    a {
      color: #262626;
      font-size: 14px;
      text-decoration: none;
    }

    &:hover, &.ant-menu-item-selected {
      color: #262626;

      a {
        color: #262626;
      }

      &::after {
        border-bottom-color: #262626;
      }
    }
  }
}

.user-actions {
  display: flex;
  justify-content: flex-end;
}

.actions-container {
  display: flex;
  align-items: center;
  position: relative;

  .action-item {
    margin-left: 15px;
    color: #262626;
    text-decoration: none;
    font-size: 13px;

    &:hover {
      color: #434343;
    }

    .iconButton {
      &:hover {
        background-color: #FFFFFF;
      }
    }
  }

  .search-icon-container {
    z-index: 11;
  }

  .login-link {
    border-right: 1px solid #e8e8e8;
    padding-right: 15px;
  }

  .user-links {
    display: flex;
    transition: opacity 0.3s ease, transform 0.3s ease;
  }

  .search-container {
    position: absolute;
    right: 135px;
    opacity: 0;
    width: 0;
    transition: all 0.3s ease;
    overflow: hidden;

    &.show-search {
      width: 180px;
      opacity: 1;
    }
  }

  .search-input {
    width: 100%;
    border-radius: 4px;

    :deep(.ant-input) {
      border-radius: 4px;
      border-color: #d9d9d9;

      &:focus {
        border-color: #262626;
        box-shadow: none;
      }
    }
  }

  .cart-total-box {
    position: relative;
    display: flex;
    align-items: center;
    justify-content: center;

    .header-icon {
      width: 26px;
      height: 26px;
    }

    .cart-total {
      position: absolute;
      top: 52%;
      left: 50%;
      transform: translate(-50%, -40%);
      font-size: 12px;
      font-weight: 600;
      color: #000;
      min-width: 16px;
      height: 16px;
      border-radius: 8px;
      display: flex;
      align-items: center;
      justify-content: center;
      line-height: 1;
      padding: 0 4px;
    }
  }

  .user-account {
    display: flex;
    align-items: center;
    cursor: pointer;
    padding: 2px 5px;
    color: #262626;

    .user-greeting {
      font-weight: 500;
      margin-right: 5px;
      font-size: 14px;
    }

    .dropdown-icon {
      font-size: 12px;
      color: #595959;
    }

    &:hover {
      color: #434343;
    }
  }
}

.user-dropdown-menu {
  min-width: 150px;
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);

  :deep(.ant-dropdown-menu-item) {
    padding: 8px 12px;
    font-size: 14px;

    a {
      color: rgba(0, 0, 0, 0.85);
      text-decoration: none;
      display: block;

      &:hover {
        color: #434343;
      }
    }

    &:hover {
      background-color: #f5f5f5;
    }
  }
}

.cart-popup {
  width: 360px;
  height: 500px;
}

.logout-text {
  font-weight: 600;
  font-size: 14px;
}
.cart-total{
  position: absolute;
  left: 56%;
  top: 56%;
  transform: translate(-50%, -50%);
  font-size: 12px;
  font-weight: 600;
  color: #000;
}
.mobile-menu {
  position: absolute;
  right: 15px;
  top: 22px;
  z-index: 1001;

  .menu-toggle {
    font-size: 20px;
  }
}

.mobile-menu-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  padding: 8px 0;
  font-size: 16px;
  color: #262626;
  text-decoration: none;
}

.submenu-header {
  display: flex;
  align-items: center;
  padding: 0 0 16px 0;
  margin-bottom: 10px;
  border-bottom: 1px solid #e8e8e8;
  font-size: 16px;
  font-weight: 500;
}

.back-button {
  margin-right: 16px;
  cursor: pointer;
}

.mobile-search-container {
  position: absolute;
  width: 100%;
  background-color: #fff;
  z-index: 1000;
  padding: 15px;
  border-bottom: 1px solid #e8e8e8;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.mobile-search-wrapper {
  max-width: 100%;
  margin: 0 auto;
}

.mobile-search-input {
  width: 100%;

  :deep(.ant-input) {
    border-radius: 4px;
    padding: 8px 12px;
    font-size: 14px;
    background-color: #f5f5f5;
    border: none;

    &:focus {
      background-color: #fff;
      border: 1px solid #d9d9d9;
      box-shadow: none;
    }
  }
}

.popular-searches {
  margin-top: 15px;

  .popular-title {
    font-size: 12px;
    color: #8c8c8c;
    margin-bottom: 8px;
  }

  .popular-item {
    display: block;
    padding: 8px 0;
    font-size: 14px;
    color: #262626;
    text-decoration: none;
    border-bottom: 1px solid #f0f0f0;

    &:last-child {
      border-bottom: none;
    }
  }
}

@media (max-width: 768px) {
  .header-container {
    padding: 0 15px;
    height: 56px;
  }

  .logo-container {
    display: flex;
    justify-content: center;

    .logo h1 {
      font-size: 24px;
    }
  }

  .user-actions {
    .user-links {
      display: none;
    }

    .search-container {
      &.show-search {
        width: 120px;
        right: 100px;
      }
    }

    .action-item {
      margin-left: 10px;
    }
  }
}
.currency-flag-container {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 20px;
  height: 20px;
  cursor: pointer;
  margin:0 0 3px 20px;
}
</style>
